package com.kitty.game.welfare.service;

import com.kitty.common.db.Db4CommonService;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.i18n.I18nId;
import com.kitty.game.map.service.MapService;
import com.kitty.game.reward.service.RewardService;
import com.kitty.game.role.model.Role;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.JsonUtils;
import com.kitty.game.utils.TimeUtil;
import com.kitty.game.welfare.WelfareDataPool;
import com.kitty.game.welfare.message.RespRechargeScoreGoodsList;
import com.kitty.game.welfare.message.vo.RechargeItem;
import com.kitty.game.welfare.model.CommonFetchedData;
import com.kitty.game.welfare.model.RechargeScoreActivitySet;
import com.kitty.game.welfare.model.RechargeScoreRewardSet;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.message.MessagePusher;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 充值积分奖励处理类
 */
@Component
public class RechargeScoreRewardHandler {
    public void loadCommonSet(Map<String, String> commonSetMap) {
        String value = commonSetMap.get("recharge_score_set");
        Map<String, String> map = Json.fromJsonAsMap(String.class, value);
        String startTimeStr = map.get("start_time");
        String endTimeStr = map.get("end_time");
        String endLineStr = map.get("end_line");

        RechargeScoreActivitySet rechargeScoreActivitySet = WelfareDataPool.rechargeScoreActivitySet;
        if (WelfareDataPool.rechargeScoreActivitySet == null) {
            WelfareDataPool.rechargeScoreActivitySet = new RechargeScoreActivitySet();
            rechargeScoreActivitySet = WelfareDataPool.rechargeScoreActivitySet;
        }

        Date date = TimeUtil.parse(startTimeStr, TimeUtil.DEFAULT_DATE_FORMAT);
        rechargeScoreActivitySet.setStartTime(date.getTime());
        date = TimeUtil.parse(endTimeStr, TimeUtil.DEFAULT_DATE_FORMAT);
        rechargeScoreActivitySet.setEndTime(date.getTime());
        date = TimeUtil.parse(endLineStr, TimeUtil.DEFAULT_DATE_FORMAT);
        rechargeScoreActivitySet.setDeadline(date.getTime());
    }

    public void loadProduct() {
        Dao dao = SpringUtils.getBean(Dao.class);
        List<RechargeScoreRewardSet> list = dao.query(RechargeScoreRewardSet.class, Cnd.NEW().asc("point"));
        Map<Byte, RechargeScoreRewardSet> rechargeScoreRewardMap = new HashMap<>();
        for (int i=0; i<list.size(); i++) {
            RechargeScoreRewardSet rechargeScoreRewardSet = list.get(i);
            rechargeScoreRewardMap.put((byte) i, rechargeScoreRewardSet);
        }
        RechargeScoreActivitySet rechargeScoreActivitySet = WelfareDataPool.rechargeScoreActivitySet;
        if (WelfareDataPool.rechargeScoreActivitySet == null) {
            WelfareDataPool.rechargeScoreActivitySet = new RechargeScoreActivitySet();
            rechargeScoreActivitySet = WelfareDataPool.rechargeScoreActivitySet;
        }
        rechargeScoreActivitySet.setRewards(list);
        rechargeScoreActivitySet.setRewardMap(rechargeScoreRewardMap);
    }

    /**加载已兑换记录*/




    /**
     * 购买充值积分奖励  积分兑换
     */
    public void buyRechargeScoreGoods(Role role, byte no, short num) {
        if (role == null ) {return ;}
        if (num <= 0) {return ;}
        if(num>100){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("数量不能超过100"));
            return;
        }
        ServerService serverService = SpringUtils.getBean(ServerService.class);
        if (serverService.getServer().getId() == 10000){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("跨服试道时，不能购买物品"));
            return;
        }
        RechargeScoreActivitySet rechargeScoreActivitySet = WelfareDataPool.rechargeScoreActivitySet;
        RechargeScoreRewardSet rechargeScoreRewardSet = rechargeScoreActivitySet.getRewardMap().get(no);
        if (rechargeScoreRewardSet == null) {
            MessagePusher.notify2Player(role, I18nId.PMT_1200);
            return ;
        }
        /**判断是否在可兑换时间内*/
        if (System.currentTimeMillis() >= rechargeScoreActivitySet.getDeadline()) {
            MessagePusher.notify2Player(role, I18nId.PMT_1203);
            return ;
        }
        /**判断玩家充值积分是否足够*/
        int needScore = rechargeScoreRewardSet.getPoint() * num;
        long total = new Long(rechargeScoreRewardSet.getPoint())*num;
        int ownScore = role.getActivity().getRechargeScore();
        if (ownScore < total) {
            MessagePusher.notify2Player(role, I18nId.PMT_1202);
            return ;
        }

        /**判断包裹是否有足够空间*/
        RewardService rewardService = SpringUtils.getBean(RewardService.class);
        if (!rewardService.checkAddReward(role, rechargeScoreRewardSet.getItem(), num)) {
            return ;
        }
        /*if (rechargeScoreRewardSet.getTotalCount() != 29999) {
            *//**减少奖励剩余数量*//*
            synchronized (this) {
                int remainCount = getRemainCount(no);
                if (remainCount < num) {
                    MessagePusher.notify2Player(role, I18nId.PMT_1201, remainCount);
                    return;
                }
                addCount(no, num);
            }
        }*/

        /**保存*/
       // saveHistory();

        SpringUtils.getRoleService().substractChargeScore(role, needScore);

        /**给奖励*/
        rewardService.addRewardItem(role, rechargeScoreRewardSet.getItem(), num);
      //  LoggerFunction.ACTIVITY.getLogger().error("buyRechargeScoreGoods|{}|{}|{}|{}", role.getUid(), Json.toJson(rechargeScoreRewardSet, JsonFormat.compact()), num, needScore);

        MessagePusher.pushMessage(role, getRespRechargeScoreGoods(role));

        /**发系统消息*/
        sendSystem(role, rechargeScoreRewardSet, num);
    }

    /**保存已兑换记录*/
    private void saveHistory() {
        String data = JsonUtils.object2String(DataCache.RECHARGE_REWARD_HISTORYS);
        CommonFetchedData fetchedData = new CommonFetchedData("recharge_score", data);
        Db4CommonService.getInstance().add2Queue(fetchedData);
    }

    /**发系统消息*/
    private void sendSystem(Role role, RechargeScoreRewardSet rechargeScoreRewardSet, int count) {
        if (StringUtils.isNotEmpty(rechargeScoreRewardSet.getSystemMsg())) {
            String content = rechargeScoreRewardSet.getSystemMsg()
                    .replaceAll("#角色名字#", role.getName())
                    .replaceAll("#道具名字#", rechargeScoreRewardSet.getItem().getName())
                    .replaceAll("#道具数量#", String.valueOf(count))
                    .replaceAll("#帮派名字#", role.getPartyName())
                    .replaceAll("#区名字#", SpringUtils.getBean(ServerService.class).getServer().getSonName())
                    .replaceAll("#地图名字#", SpringUtils.getBean(MapService.class).getMap(role.getPos().getMapId()).getName());

            SpringUtils.getChatService().sendSystem(content, Const.BRODCAST_MSG_TYPE_ROLE);
        }
    }

    /**显示奖励内容*/
    public void viewRechargeScoreGoods(Role role) {
        RespRechargeScoreGoodsList respRechangeScoreGoods = getRespRechargeScoreGoods(role);
        MessagePusher.pushMessage(role, respRechangeScoreGoods);
    }

    private RespRechargeScoreGoodsList getRespRechargeScoreGoods(Role role) {
        // mod tao: 重新load充值好礼
        (SpringUtils.getBean(RechargeScoreRewardHandler.class)).loadProduct();
        // mod:e

        RespRechargeScoreGoodsList respRechargeScoreGoodsList = new RespRechargeScoreGoodsList();

        RechargeScoreActivitySet rechargeScoreActivitySet = WelfareDataPool.rechargeScoreActivitySet;
        respRechargeScoreGoodsList.setStartTime((int) (rechargeScoreActivitySet.getStartTime()/TimeUtil.ONE_SECOND));
        respRechargeScoreGoodsList.setEndTime((int) (rechargeScoreActivitySet.getEndTime()/TimeUtil.ONE_SECOND));
        respRechargeScoreGoodsList.setDeadline((int) (rechargeScoreActivitySet.getDeadline()/TimeUtil.ONE_SECOND));
        respRechargeScoreGoodsList.setOwnPoint(role.getActivity().getRechargeScore());
        respRechargeScoreGoodsList.setTotalPoint(role.getActivity().getTotalRechargeScore());

        List<RechargeItem> rechargeItems = new ArrayList<>();
        List<RechargeScoreRewardSet> rewards = rechargeScoreActivitySet.getRewards();
        for (byte i=0; i<rewards.size(); i++) {
            RechargeScoreRewardSet rewardSet = rewards.get(i);
            RechargeItem rechargeItem = new RechargeItem();
            rechargeItem.setNo(i);
            rechargeItem.setRewardStr(rewardSet.getItem().getDesc());
            rechargeItem.setPoint(rewardSet.getPoint());
            rechargeItem.setNum(getRemainCount(i));

            rechargeItems.add(rechargeItem);
        }
        respRechargeScoreGoodsList.setItemList(rechargeItems);

        return respRechargeScoreGoodsList;
    }

    /**获得剩余数量*/
    private short getRemainCount(byte no) {
        RechargeScoreActivitySet rechargeScoreActivitySet = WelfareDataPool.rechargeScoreActivitySet;
        RechargeScoreRewardSet rewardSet = rechargeScoreActivitySet.getRewardMap().get(no);
        short aa =  (short) (rewardSet.getTotalCount() - getHasCount(no));
        if (aa < 0){
            aa = 0;
        }
        return aa;
    }

    /**获得已兑换数量*/
    private short getHasCount(byte no) {
        return DataCache.RECHARGE_REWARD_HISTORYS.getOrDefault(no, (short)0);
    }

    /**添加已兑换数量*/
    private void addCount(byte no, short count) {
        short hasCount = getHasCount(no);
        DataCache.RECHARGE_REWARD_HISTORYS.put(no, (short) (hasCount + count));
        // 快卖完的时候自动补满
//        if (hasCount > 29990){
//            DataCache.RECHARGE_REWARD_HISTORYS.put(no, (short) 0);
//        }
    }
}
